from django.shortcuts import render, redirect, HttpResponse
# messages的使用
from django.contrib import messages
from mardan import models
from mardan.utils.form import UserModelForm
from mardan.utils.pagination import Pagination


# 首页
def index(request, nid=1):
    if request.method == "GET":
        ############搜索框的实现#############
        data_dict = {}
        kuang_data = request.GET.get('q', '')  # 获取框的url和值
        category_list = models.Category.objects.all()
        if kuang_data:  # 当框的在驾校名包含的时候
            data_dict["gname__contains"] = kuang_data
            goods_list = models.Goods.objects.filter(gname__contains=kuang_data)
            print(goods_list)
            page_object = Pagination(request, goods_list, page_size=20)  # 添加分页功能肄业20条记录
            context = {
                "goods_list": page_object.page_queryset,
                "page_string": page_object.html(),
                "category_list": category_list,
                "nid": nid,
                "kuang_data": kuang_data
            }
            return render(request, 'index.html', context)
        goods_list = models.Goods.objects.filter(Category_id=nid, **data_dict)
        if len(goods_list) == 0:
            page_object = Pagination(request, goods_list, page_size=20)  # 添加分页功能肄业20条记录
            context = {
                "goods_list": page_object.page_queryset,
                "page_string": page_object.html(),
                "category_list": category_list,
                "nid": nid,
                "kuang_data": kuang_data
            }
            return render(request, 'index.html', context)
        page_object = Pagination(request, goods_list, page_size=20)  # 添加分页功能肄业20条记录
        context = {
            "goods_list": page_object.page_queryset,
            "page_string": page_object.html(),
            "category_list": category_list,
            "nid": nid,
            "kuang_data": kuang_data
        }
        return render(request, 'index.html', context)


def user_index(request, nid=1):
    """ 返回登录过后的首页 """
    info = request.session.get("info")
    if not info:
        return redirect('/login')
    if request.method == "GET":
        ############搜索框的实现#############
        data_dict = {}
        kuang_data = request.GET.get('q', '')  # 获取框的url和值
        category_list = models.Category.objects.all()
        if kuang_data:  # 当框的在班级名包含的时候
            data_dict["gname__contains"] = kuang_data
            goods_list = models.Goods.objects.filter(gname__contains=kuang_data)
            print(goods_list)
            page_object = Pagination(request, goods_list, page_size=20)  # 添加分页功能肄业20条记录
            context = {
                "goods_list": page_object.page_queryset,
                "page_string": page_object.html(),
                "category_list": category_list,
                "nid": nid,
                "kuang_data": kuang_data
            }
            return render(request, 'index.html', context)
        goods_list = models.Goods.objects.filter(Category_id=nid, **data_dict)
        print(goods_list)
        if len(goods_list) == 0:
            if len(kuang_data) == 0:
                print(kuang_data)
                goods_list = models.Goods.objects.filter(gname__contains=kuang_data)
            print(goods_list)
            page_object = Pagination(request, goods_list, page_size=20)  # 添加分页功能肄业20条记录
            context = {
                "goods_list": page_object.page_queryset,
                "page_string": page_object.html(),
                "category_list": category_list,
                "nid": nid,
                "kuang_data": kuang_data
            }
            return render(request, 'index.html', context)
<<<<<<< HEAD
        page_object = Pagination(request, goods_list, page_size=20)
=======
        page_object = Pagination(request, goods_list, page_size=20)  # 添加分页功能肄业20条记录
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
        context = {
            "goods_list": page_object.page_queryset,
            "page_string": page_object.html(),
            "category_list": category_list,
            "nid": nid,
            "kuang_data": kuang_data
        }
        return render(request, 'user-index.html', context)


def zhuce(request):
    """ 注册用户 """
    if request.method == "GET":
        form = UserModelForm()  # 生成user_add.html输入框
        return render(request, 'user_add.html', {"form": form})  # 返回到注册页面
    # 用户POST提交数据，数据校验。
    form = UserModelForm(data=request.POST, files=request.FILES)
    print(request.FILES)
    if form.is_valid():
        # 如果数据合法，保存到数据库
        form.save()
        return redirect('/login/')  # 校验完以后跳转到登录页面
    # 校验失败（在页面上显示错误信息）
    return render(request, 'user_add.html', {"form": form})


def zhaohuipwd(request):
    """找回密码"""
    if request.method == "GET":
        return render(request, "zhaohui_mima.html")
    username = request.POST.get("username")
    dianhua = request.POST.get("dianhua")
    email = request.POST.get("email")
    pwd = request.POST.get("pwd")
    pwd1 = request.POST.get("pwd1")
    queryset = models.Yonghu.objects.filter(username=username).values()
    if queryset.count() == 0:
        return redirect('/zhuce')
    querysetdianhua = models.Yonghu.objects.filter(username=username).values("dianhua").first()["dianhua"]  # 获取该用户的手机号
    querysetemail = models.Yonghu.objects.filter(username=username).values("email").first()["email"]  # 获取该用户的邮箱
    # print(querysetdianhua, querysetemail, type(querysetdianhua), type(querysetemail))
    if dianhua == querysetdianhua and email == querysetemail:
        if pwd == pwd1:
            queryset = models.Yonghu.objects.filter(username=username).values().update(password=pwd)
            return redirect('/login')
        if pwd != pwd1:
            return redirect('/zhaohuipwd')
    return redirect('/zhaohuipwd')


def userinfo(request):
    """ 个人信息 """
    info = request.session.get("info")
    if not info:
        return redirect('/login')
    info_dict = request.session["info"]  # 获取写到数据库的sessin。为了获得当前登录用户的id
    # print("用户id为：{}".format(info_dict["id"]))
    # print("用户名为：{}".format(info_dict["name"]))
    queryset = models.Yonghu.objects.all().filter(id=info_dict["id"])  # 根据当前的用户id筛选个人数据
    return render(request, "userifo.html", {"queryset": queryset})


def user_edit(request, nid):
    """ 修改个人信息"""
    info = request.session.get("info")
    if not info:
        return redirect('/login')
    row_object = models.Yonghu.objects.filter(id=nid).first()
    print(row_object)
    if request.method == "GET":
        # 根据ID去数据库获取要编辑的那一行数据（对象）
        form = UserModelForm(instance=row_object)
        return render(request, 'user_edit.html', {'form': form})

    form = UserModelForm(data=request.POST, instance=row_object)
    if form.is_valid():
        form.save()
        return redirect('/user/info/')
    return render(request, 'user_edit.html', {"form": form})


def user_delete(request, nid):
    """ 删除用户 """
    info = request.session.get("info")
    if not info:
        return redirect('/login/')
    models.Yonghu.objects.filter(id=nid).delete()
    # return HttpResponse("成功")
    return redirect("/index/1/")


# 驾校详细信息
def goodsdetails(request, nid):
    if request.method == "GET":
        queryset = models.Goods.objects.filter(id=nid)
        msg = request.GET.get('param')
        err = request.GET.get('paramerr')
        red = request.GET.get('red')
        # print(err)
        return render(request, 'detail.html', {"queryset": queryset, "msg": msg, "err": err, "red": red})


# from django.views import View
# class CartView(View):
#     def post(self,request):
#         flag=request.POST.get('flag','')
#         if flag=='add':
def addcart(request):
    if request.method == "GET":
        return HttpResponse("报名成功")
    if request.method == "POST":
        flag = request.POST.get('flag', '')
        goodsid = request.POST.get('goodsid', '')
        gname = request.POST.get('gname', '')
        colorurl = request.POST.get('colorurl', '')
        sname = request.POST.get('sname', '')
        Category = request.POST.get('Category', '')
        price = request.POST.get('price', '')
        if flag == '加入收藏':
            info = request.session.get("info")
            if not info:
                return redirect('/login/')
            # 获取当前用户session信息
            info_dict = request.session.get("info")
            user = info_dict["id"]
            dianhua = models.Yonghu.objects.filter(id=user).values('dianhua')
            print(user)
<<<<<<< HEAD
            models.Cart.objects.create(goodsid=goodsid, user_id=user, dianhua=dianhua, colorurl=colorurl,
                                       Category=Category,
                                       sname=sname, gname=gname, price=price, )
=======
            models.Cart.objects.create(goodsid=goodsid, user_id=user,dianhua=dianhua,colorurl=colorurl, Category=Category,
                                       sname=sname, gname=gname, price=price)
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
            return redirect('/mycart/')
        if flag == '报名':
            info = request.session.get("info")
            if not info:
                return redirect('/login/')
<<<<<<< HEAD

            info_dict = request.session.get("info")
            user = info_dict["id"]
            if len(models.Order.objects.filter(user=user, enlist=1)) >= 1:
                messages.add_message(request, messages.SUCCESS, '你已经报名，不能重复报名!')
                return render(request, "detail.html")
            yonghu = models.Yonghu.objects.filter(id=user).values('head', 'dianhua', 'age', 'idnumber', 'gender')
=======
            # print("goodsid:",goodsid)
            # print("flag:",flag)
            # print(gname)
            # print(colorurl)
            info_dict = request.session.get("info")
            user = info_dict["id"]
            # print(user)
            # print(len(models.Order.objects.filter(user=user)))
            if len(models.Order.objects.filter(user=user)) >= 1:
                messages.add_message(request, messages.SUCCESS, '你已经报名，不能重复报名!')
                return render(request,"detail.html")
            yonghu = models.Yonghu.objects.filter(id=user).values('head','dianhua','age','idnumber','gender')
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
            obj = {}
            print(yonghu)
            for i in yonghu:
                print(i['head'])
                obj.setdefault('head', i['head'])
                obj.setdefault('dianhua', i['dianhua'])
                obj.setdefault('age', i['age'])
                obj.setdefault('idnumber', i['idnumber'])
                obj.setdefault('gender', i['gender'])
            print(obj['idnumber'])
<<<<<<< HEAD
            models.Order.objects.create(goodsid=goodsid, user_id=user, head=obj['head'], age=obj['age'],
                                        idnumber=obj['idnumber'], gender=obj['gender'], colorurl=colorurl,
                                        dianhua=obj['dianhua'], Category=Category,
                                        sname=sname, gname=gname, price=price, enlist=1)
=======
            models.Order.objects.create(goodsid=goodsid, user_id=user,head=obj['head'],age=obj['age'],idnumber=obj['idnumber'],gender=obj['gender'], colorurl=colorurl,dianhua=obj['dianhua'], Category=Category,
                                       sname=sname, gname=gname, price=price)
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
            models.Yonghu.objects.filter(id=user).update(gname=gname)
            return redirect('/orders/')


def mycart(request):
    if request.method == "GET":
        info = request.session.get("info")
        if not info:
            return redirect('/login/')
        name = info['id']
        queryset = models.Cart.objects.filter(user=name)
        print(name)
        context = {
            "queryset": queryset,
        }
        return render(request, 'mycart.html', context)
    if request.method == "POST":
        id = request.POST.get('cartgoodsid', '')
        goodsid = request.POST.get('goodsid', '')
        price = request.POST.get('price', '')
        sname = request.POST.get('sname', '')
        Category = request.POST.get('Category', '')
        colorurl = request.POST.get('colorurl1', '')
        gname = request.POST.get('gname', '')
        info = request.session.get("info")
        print(info)
        if not info:
            return redirect('/login/')
        queryset = models.Order.objects.filter(status=0)
        print(queryset)
        info_dict = request.session.get("info")
        user = info_dict["id"]
<<<<<<< HEAD
        print(user)
        if len(models.Order.objects.filter(user=user, enlist=1)) >= 1:
            messages.add_message(request, messages.SUCCESS, '你已经报名，不能重复报名!')
            return render(request, "detail.html")
        yonghu = models.Yonghu.objects.filter(id=user).first()
        print(yonghu.age)
        models.Cart.objects.filter(pk=id).update()
        models.Order.objects.create(goodsid=goodsid, user_id=user, colorurl=colorurl, dianhua=yonghu.dianhua,
                                    age=yonghu.age,
                                    Category=Category, gender=yonghu.gender, head=yonghu.head, idnumber=yonghu.idnumber,
                                    sname=sname, gname=gname, price=price, enlist=1)
=======
        if len(models.Order.objects.filter(user=user)) >= 1:
            messages.add_message(request, messages.SUCCESS, '你已经报名，不能重复报名!')
            return render(request, "detail.html")
        dianhua = models.Yonghu.objects.filter(id=user).values('dianhua')
        models.Cart.objects.filter(pk=id).update()
        models.Order.objects.create(goodsid=goodsid, user_id=user, colorurl=colorurl, dianhua=dianhua,
                                    Category=Category,
                                    sname=sname, gname=gname, price=price)
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
        models.Yonghu.objects.filter(id=user).update(gname=gname)
        return redirect('/orders/')


def mycartdelete(request, id):
    models.Cart.objects.filter(id=id).delete()
    # 1.定义messages
    messages.add_message(request, messages.SUCCESS, '已经取消收藏!')
    return redirect('/mycart/')


def orders(request):
    if request.method == "GET":
        info = request.session.get("info")
        if not info:
            return redirect('/login/')
<<<<<<< HEAD
        queryset = models.Order.objects.filter(user=info['id'], enlist=1)
        for order in queryset:
            print(order.order_date)
=======
        queryset = models.Order.objects.all()
        for order in queryset:
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
            if order.status == 2:
                return render(request, 'orders.html', {"queryset": queryset})
        return render(request, 'orders.html', {"queryset": queryset})

<<<<<<< HEAD

def ordersdelete(request, id):
    data = models.Order.objects.filter(status=3)
    print(data)
    models.Order.objects.filter(id=id).update(enlist=2)
=======
def ordersdelete(request, id):
    data = models.Order.objects.filter(status=3)
    print(data)
    models.Order.objects.filter(id=id).delete()
>>>>>>> f0eb04185cbc15f17a793618efb075babdcd937b
    # 1.定义messages
    messages.add_message(request, messages.SUCCESS, '已经取消报名!')
    return redirect('/orders/')
